/**
 * 
 */
package com.vit.mep.manager;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.crypto.CryptoException;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.vit.mep.HttpPost;
import com.vit.mep.MepException;
import com.vit.mep.model.MepUser;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransport;

/**
 * @author crodriguez
 *
 */
public class LoginManager {
	
	public static final String _ACTIVE = "ACTIVE";

	public MepUser login(MepUser user) throws MepException{
		ManagerUtils utils = new ManagerUtils();
		
		String passwordEncryp = "";
		String passByte = null;
		byte[] keyData;
		
		try {
			
			passwordEncryp = utils.encrypt(user.getPassword().getBytes());
	        	        
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}//key for test remember change later
         catch (CryptoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//URLEncodedPostData _postData = new URLEncodedPostData("",false);
		String resultXml = "";
		
		
		//String password = utils.generateEncrypted(user.getPassword()); 
		
	//	String postUrl = "?user=" + user.getUsername() + "&password=" + password + "&format=xml";
	//	HttpPost _httpPost=new HttpPost(ManagerConstants._LOGIN_SERVICE + postUrl  , _postData,"POST");
	//	resultXml=_httpPost.executeMethodPOST_INPUT_DELETE();
				
				
		MepUser returnUser = null;	
		try {
			//returnUser = parseLoginResponse(resultXml);
			
			resultXml =	loginWs (user.getUsername(),passwordEncryp);
						
			if (resultXml.toUpperCase().equalsIgnoreCase("TRUE")){
				returnUser = new MepUser();		
			returnUser.setName1("eduardo");
			returnUser.setName1("antonio");
			returnUser.setFamilyName1("FamilyName1");
			returnUser.setFamilyName2("FamilyName2");
							
			}
							
		} catch (Exception e) {
			MepException me = new MepException();
			me.setAditionalMessage(e.getMessage() + "-->" + resultXml);
			throw me;			
		}finally{
		//	_httpPost.closeConnection();
		}
		
		return returnUser;
	}
	
		
	private MepUser parseLoginResponse(String xml) throws Exception{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());			
		Document doc  = db.parse(bis);
		doc.normalize();
		MepUser user = new MepUser();
		
		String str = getUniqueNodeValue("username", doc);
		user.setUsername(str);
		str = getUniqueNodeValue("name1", doc);
		user.setName1(str);
		str = getUniqueNodeValue("name2", doc);
		user.setName2(str);
		str = getUniqueNodeValue("familyName1", doc);
		user.setFamilyName1(str);
		str = getUniqueNodeValue("familyName2", doc);
		user.setFamilyName2(str);
		str = getUniqueNodeValue("password", doc);		
		user.setPassword(str);
		
		str = getUniqueNodeValue("id", doc);		
		user.setId(str);
		
		return user;
	}
	
	
	private String getUniqueNodeValue(String nodeName, Document doc){
		
		String result  = "";
		NodeList nl = doc.getElementsByTagName(nodeName);
		Node node =  nl.item(0);
		if(node != null){
			result = node.getChildNodes().item(0).getNodeValue();	
		}
		if(result!= null) result = result.trim();
		
		return result;
	}
	
	
	public String loginWs(String user, String pass) {
			
		try {
			
			String nameSpace = "http://webServices";
			String methodName = "loginUser";
			String soapAction = nameSpace + "/"+ methodName;
			          
			String URL = "http://localhost:8080/MepWs/services/MepWs;deviceside=true";
			         
			SoapObject soapObj = new SoapObject(nameSpace, methodName);
			soapObj.addProperty("user", user);
			soapObj.addProperty("pass", pass);
									
			SoapSerializationEnvelope envelope = new  SoapSerializationEnvelope(SoapEnvelope.VER10);
			envelope.bodyOut = soapObj;
			envelope.dotNet = false;
									
			HttpTransport httpTrans = new HttpTransport(URL);
						
			httpTrans.debug = true;
		
			String result = null;
			
			try
			{
				httpTrans.call(soapAction, envelope);
			
		    //	SoapObject x = (SoapObject)envelope.bodyIn;
			
		      result =  envelope.getResponse().toString();
		      
		      return result.toString();
		      
			}
			catch(org.xmlpull.v1.XmlPullParserException ex2){
				
				return   ex2.toString();
			}
			
			}
			catch(Exception ex){
				
			    return   ex.toString();
			}
			
		}
	
	
	protected String createXML(MepUser user){	
		ManagerUtils mu = new ManagerUtils();			
		String xml = "";		
		String usr = mu.inXmlTag("usuario", user.getUsername());
		String pass = mu.inXmlTag("password", mu.generateEncrypted(user.getPassword()));		
		xml +="<mep>";
		xml += usr + pass;
		xml +="</mep>";		
		return xml;
	} 
	
	
	
}//class